<template>
  <el-cascader
    v-model="selectedRegion"
    :options="regionOptions"
    :props="cascaderProps"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :size="size"
    :filterable="filterable"
    @change="handleChange"
  />
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, nextTick } from 'vue'
  import { loadCascaderData } from '@/utils/regionDataManager'

  // 定义组件属性
  const props = withDefaults(
    defineProps<{
      modelValue: string | number | (string | number)[] | null
      placeholder?: string
      clearable?: boolean
      disabled?: boolean
      size?: 'large' | 'default' | 'small'
      filterable?: boolean
      emitPath?: boolean
    }>(),
    {
      placeholder: '请选择地区',
      clearable: true,
      disabled: false,
      size: 'default',
      filterable: true,
      emitPath: true,
    }
  )

  // 定义事件
  const emit = defineEmits<{
    'update:modelValue': [value: string | number | (string | number)[] | null]
    change: [value: any, selectedOptions: any[]]
  }>()

  // 响应式数据
  const selectedRegion = ref<(string | number)[] | null>(null)
  const regionOptions = ref<any[]>([])

  // 级联选择器配置
  const cascaderProps = {
    checkStrictly: false,
    emitPath: true, // 保持为true，让el-cascader自动处理路径
    value: 'id', // 使用id作为value字段
    label: 'name', // 使用name作为label字段
    children: 'children',
    expandTrigger: 'hover' as const,
  }

  // 加载地区数据
  const loadRegionData = async () => {
    console.log('开始加载地区数据...')
    try {
      const data = await loadCascaderData()
      console.log('地区数据加载成功，数据长度:', data.length)
      console.log('地区数据内容:', JSON.stringify(data.slice(0, 2), null, 2))

      regionOptions.value = data
      console.log('regionOptions设置完成，长度:', regionOptions.value.length)

      // 数据加载完成后，如果有初始值，初始化选中状态
      if (props.modelValue) {
        await nextTick()
        initSelectedRegion()
      }
    } catch (error) {
      console.error('地区数据加载失败:', error)
    }
  }

  // 初始化选中值
  const initSelectedRegion = () => {
    console.log('初始化选中值，当前modelValue:', props.modelValue)

    if (!props.modelValue) {
      selectedRegion.value = null
      return
    }

    // 处理不同类型的输入值
    if (typeof props.modelValue === 'string') {
      // 字符串格式：'110000/110100/110101'
      if (props.modelValue.includes('/')) {
        selectedRegion.value = props.modelValue.split('/').map(id => parseInt(id, 10))
      } else {
        selectedRegion.value = [parseInt(props.modelValue, 10)]
      }
      console.log('字符串值转换为数组:', selectedRegion.value)
    } else if (Array.isArray(props.modelValue)) {
      // 数组格式：[110000, 110100, 110101]
      selectedRegion.value = props.modelValue.map(id => {
        if (typeof id === 'number') {
          return id
        } else {
          return parseInt(String(id), 10)
        }
      })
      console.log('使用数组值:', selectedRegion.value)
    } else {
      // 处理数字类型
      selectedRegion.value = [props.modelValue]
      console.log('单个值转换为数组:', selectedRegion.value)
    }
  }

  // 处理选择变化
  const handleChange = (value: any) => {
    console.log('选择变化，原始值:', value)

    let emitValue: string | number[] | null

    if (!value || (Array.isArray(value) && value.length === 0)) {
      // 如果没有选择任何值
      emitValue = props.emitPath ? '' : []
      selectedRegion.value = null
    } else if (props.emitPath) {
      // 如果emitPath为true，返回字符串格式
      emitValue = Array.isArray(value) ? value.join('/') : String(value)
    } else {
      // 如果emitPath为false，返回数组格式
      emitValue = value
    }

    console.log('emitPath:', props.emitPath, 'emitValue:', emitValue)

    // 更新内部值
    selectedRegion.value = value

    // 更新v-model
    emit('update:modelValue', emitValue)

    // 触发change事件
    const selectedOptions = getSelectedOptions(value)
    emit('change', emitValue, selectedOptions)
  }

  // 获取选中的选项信息
  const getSelectedOptions = (value: any[]): any[] => {
    if (!value || !Array.isArray(value) || value.length === 0) {
      return []
    }

    const result: any[] = []
    let currentOptions = regionOptions.value

    for (const id of value) {
      const found = currentOptions.find(option => option.id === id)
      if (found) {
        result.push(found)
        currentOptions = found.children || []
      } else {
        break
      }
    }

    return result
  }

  // 监听modelValue变化
  watch(
    () => props.modelValue,
    newValue => {
      console.log('modelValue变化:', newValue)
      initSelectedRegion()
    },
    { immediate: true }
  )

  // 组件挂载时加载数据
  onMounted(() => {
    loadRegionData()
  })
</script>

<style scoped>
  /* 组件样式 */
</style>
